package org.xhnews.utils;

import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import org.xhnews.log.RaspberryLogger;

public class FileUtil {
	public static final String RootOfFilesystem = "file:///SDCard/";

	public static void makePicDir(String dirname) {
		FileConnection fc;
		try {
			fc = (FileConnection) Connector.open(RootOfFilesystem+dirname,
					Connector.READ_WRITE);
			if (!fc.exists()) {
				fc.mkdir();
			} else {
				boolean isfolder = fc.isDirectory();
				if (!isfolder) {
					return;
				}
			}
			fc.close();
		} catch (Exception e) {
			e.printStackTrace();
			RaspberryLogger.getInstance().info(e.getMessage());
		}
	}

	public static void deleteFile(String dirname, String filename) {
		FileConnection fc = null;
		try {
			fc = (FileConnection) Connector.open(RootOfFilesystem + dirname
					+ filename, Connector.READ_WRITE);
			if (fc.exists() && fc.fileSize() == 0) {
				fc.delete();
			}
			fc.close();
		} catch (Exception e) {
			e.printStackTrace();
			RaspberryLogger.getInstance().info(e.getMessage());
		}
	}

	public static byte[] readFile(String dirname, String filename) {
		FileConnection fc = null;
		byte[] bytes = null;
		try {
			fc = (FileConnection) Connector.open(RootOfFilesystem + dirname
					+ filename, Connector.READ_WRITE);
			if (fc.exists()) {
				InputStream dis = fc.openInputStream();
				int size = (int) fc.fileSize();
				bytes = new byte[size];
				dis.read(bytes, 0, bytes.length);
				dis.close();
			}
			fc.close();
			return bytes;
		} catch (Exception e) {
			e.printStackTrace();
			RaspberryLogger.getInstance().info(e.getMessage());
			return null;
		}
	}

	public static void writeFile(String dirname, String filename, InputStream is) {
		FileConnection fc = null;
		try {
			fc = (FileConnection) Connector.open(RootOfFilesystem + dirname
					+ filename, Connector.READ_WRITE);
			// 已存在返回
			if (fc.exists()) {
				fc.close();
				return;
			}
			// 不存在，创建文件
			fc = (FileConnection) Connector.open(RootOfFilesystem + dirname
					+ filename, Connector.READ_WRITE);
			fc.create();
			OutputStream os = fc.openOutputStream();
			int ch = 0;
			while ((ch = is.read()) != -1) {
				os.write(ch);
			}
			os.close();
//			fc.rename(filename);
			fc.close();
		} catch (Exception e) {
			RaspberryLogger.getInstance().info(e.getMessage());
			e.printStackTrace();
		}
	}
}
